<?php
include_once('config/config.php');
date_default_timezone_set('UTC');
$depData = dbAll("SELECT * FROM `department`");

if ($_POST) {
  $params = $_POST;

  $action = $_POST['action'];
  if ($action == 'checkDepid') {
    $depid = $_POST['depid'];
    $allJob = dbAll("SELECT * FROM `job` WHERE `depid` = '$depid'");
    if (!empty($allJob)) {
      success('职位表查询成功', $allJob);
    } else {
      error('职位表查询失败');
    }
  }
  if ($action == 'checkName') {
    $name = $_POST['name'];
    if (empty(trim($name))) {
      error('用户名不能为空');
    }
    $NameId = dbFind("SELECT `id` FROM `person` WHERE `name` = '$name'");
    if ($NameId) {
      error('用户名已经存在');
    } else {
      success('用户名可以使用');
    }
  }

  if ($action == 'checkMobile') {
    $mobile = $_POST['mobile'];
    if (empty(trim($mobile))) {
      error('手机号码不能为空');
    } else if (strlen($mobile) == "11") {
      $reg = "/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$/";
      if (!preg_match($reg, $mobile)) {
        error("手机号不正确");
      }
      $MobileId = dbFind("SELECT `id` FROM `person` WHERE `mobile` = '$mobile'");
      if ($MobileId) {
        error('手机号码已经存在');
      } else {
        success('手机号码可以使用');
      }
    } else {
      error("手机号长度必须是11位");
    }
  }

  if ($action == 'checkEmail') {
    $email = $_POST['email'];
    if (empty(trim($email))) {
      error('邮箱不能为空');
    } else if(!preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/',$email)){
      error("邮箱不合法");
    } else {
      $EmailId = dbFind("SELECT `id` FROM `person` WHERE `email` = '$email'");
      if ($EmailId) {
        error('邮箱已经存在');
      } else {
        success('邮箱可以使用');
      }
    }
  }

  $avatar = upload('avatar');

  //检查上传图片的数据
  if ($avatar['code'] == 0) {
    ShowMsg($avatar['msg']);
    exit;
  }
  if (empty($params['jobid'])) {
    ShowMsg('没有选择职位');
    exit;
  }
  //封装数组
  $data = [
    'name' => $params['name'],
    'avatar' => $avatar['data'],
    'mobile' => $params['mobile'],
    'sex' => $params['sex'],
    'email' => $params['email'],
    'address' => $params['address'],
    'depid' => $params['depid'],
    'jobid' => $params['jobid'],
    'createtime' => time(),
  ];
  //新增新数据到数据库
  $res = dbAdd('person', $data);
  if ($res) {
    ShowMsg('新增成功', 'personList.php');
    exit;
  } else {
    ShowMsg('新增失败');
    exit;
  }
  //返回新增成功的新增id
  // pre($res);

  exit;
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <!-- 引用公共头部 -->
  <?php include_once('common/meta.php'); ?>

  <style>
    #avatar {
      width: 200px;
      user-select: none;
    }

    #img {
      width: 200px;
      display: block;
    }

    .icon-list {
      margin-right: 5px;
    }
  </style>
</head>

<body>
  <meta charset="utf-8">
  <title>员工</title>
  <!-- 引用公共头部 -->
  <?php include_once('common/header.php'); ?>

  <!-- 引用侧边菜单 -->
  <?php include_once('common/sidebar.php'); ?>

  <div class="content">
    <div class="header">
      <h1 class="page-title">新增员工</h1>
    </div>
    <ul class="breadcrumb">
      <li><a href="index.php">首页</a> <span class="divider">/</span></li>
      <li class="active">员工</li>
    </ul>

    <div class="container-fluid">
      <div class="row-fluid">

        <div class="btn-toolbar">
          <button class="btn btn-primary " onClick="location='personList.php'"><i class="icon-list"></i>员工</button>
          <div class="btn-group">
          </div>
        </div>

        <div class="well">
          <div id="myTabContent" class="tab-content">
            <div class="tab-pane active in" id="home">
              <form method="POST" enctype="multipart/form-data">

                <label>用户名</label>
                <input type="text" value="" class="input-xxlarge" name="name" placeholder="请输入用户名" required>
                <span id="name" style="margin-left: 10px;"></span>

                <label>手机号码</label>
                <input type="text" value="" class="input-xxlarge" name="mobile" οninput="value=value.replace(/[^\d]/g,'')" maxlength="11" placeholder="请输入手机号码" required>
                <span id="mobile" style="margin-left: 10px;"></span>

                <label>性别</label>
                <!-- <select name="sex">
                  <option value="0">保密</option>
                  <option value="1" selected>女</option>
                  <option value="2">男</option>
                </select> -->

                <div class="layui-inline">
                  <div class="layui-input-inline" style="width:123px;display:flex;display: flex;justify-content: space-between;">
                    <input type="radio" id="radio0" name="sex" value="0" title="保密"><label for="radio0">保密</label>
                    <input type="radio" id="radio1" name="sex" value="1" title="女" checked><label for="radio1">女</label>
                    <input type="radio" id="radio2" name="sex" value="2" title="男"><label for="radio2">男</label>
                  </div>
                </div>

                <label>邮箱</label>
                <input type="text" value="" class="input-xxlarge" name="email" placeholder="请输入邮箱" required>
                <span id="email" style="margin-left: 10px;"></span>

                <label>地址</label>
                <input type="text" value="" class="input-xxlarge" name="address" placeholder="请输入地址" required>

                <label>部门</label>
                <select name="depid" require>
                  <option id="depidChage">请选择</option>
                  <?php foreach ($depData as $item) { ?>
                    <option value="<?php echo $item['id']; ?>"><?php echo $item['name']; ?></option>
                  <?php } ?>
                </select>

                <label>职位</label>
                <select name="jobid" id="jobid" require>
                  <option value="">请选择</option>
                </select>


                <label>头像</label>
                <input type="file" value="" class="input-xxlarge" id="avatar" name="avatar" hidden required>
                <label class="avatar" for="avatar">
                  <img src="static/images/upload.png" id="img">
                </label>

                <input class="btn btn-primary" type="submit" value="提交" />
              </form>
            </div>
          </div>
        </div>

        <!-- 引用公共底部 -->
        <?php include_once('common/footer.php'); ?>

      </div>
    </div>
  </div>
</body>

</html>
<!-- 引用script -->
<?php include_once('common/script.php'); ?>
<script>
  // 图片预览函数
  function GetObjectURL(file) {
    // createObjectURL  给一个文件对象 可以提取出一个url本地地址出来
    var url = null;

    //判断是否为IE浏览器还是google还是其他浏览器
    if (window.createObjectURL != undefined) {
      url = window.createObjectURL(file)
    } else if (window.URL != undefined) {
      url = window.URL.createObjectURL(file)
    } else if (window.webkitURL != undefined) {
      url = window.webkitURL.createObjectURL(file)
    }

    return url
  }
  $('#avatar').change(function() {

    // 获取选中的文件
    let file = $(this)[0].files[0] ? $(this)[0].files[0] : {};


    // 获取文件地址
    let url = GetObjectURL(file)
    $('#img').attr('src', url);
  });

  $('select[name="depid"]').change(function() {
    let depid = $(this).val();
    $('#depidChage').css({
      "display": "none"
    });
    $.ajax({
      type: 'post',
      url: 'personAdd.php',
      data: {
        depid,
        action: 'checkDepid'
      },
      dataType: 'json',
      success: function(res) {
        if (res.code === 1) {
          let option = '';

          res.data.forEach((item) => {
            option += `<option value="${item.id}">${item.name}</option>`
          });
          $('#jobid').html(option);
        } else {
          $('#jobid').html(`<option value="">无</option>`);
        }
      },
      error: function(error) {
        console.log(error)
      }
    })
  });

  $('input[name="name"]').change(function() {
    let name = $(this).val();

    $.ajax({
      type: 'post',
      url: 'personAdd.php',
      data: {
        name,
        action: 'checkName'
      },
      dataType: 'json',
      success: function(res) {
        if (res.code === 1) {
          $('#name').html(res.msg).css({
            "color": "green"
          })
        } else {
          $('#name').html(res.msg).css({
            "color": "red"
          })
        }
      },
      // 请求失败的回调函数 404 301 500等
      error: function(error) {
        console.log(error)
      }
    })
  });

  $('input[name="mobile"]').change(function() {
    let mobile = $(this).val();

    $.ajax({
      type: 'post',
      url: 'personAdd.php',
      data: {
        mobile,
        action: 'checkMobile'
      },
      dataType: 'json',
      success: function(res) {
        if (res.code === 1) {
          $('#mobile').html(res.msg).css({
            "color": "green"
          })
        } else {
          $('#mobile').html(res.msg).css({
            "color": "red"
          })
        }
      },
      // 请求失败的回调函数 404 301 500等
      error: function(error) {
        console.log(error)
      }
    })
  });

  $('input[name="email"]').change(function() {
    let email = $(this).val();

    $.ajax({
      type: 'post',
      url: 'personAdd.php',
      data: {
        email,
        action: 'checkEmail'
      },
      dataType: 'json',
      success: function(res) {
        if (res.code === 1) {
          $('#email').html(res.msg).css({
            "color": "green"
          })
        } else {
          $('#email').html(res.msg).css({
            "color": "red"
          })
        }
      },
      // 请求失败的回调函数 404 301 500等
      error: function(error) {
        console.log(error)
      }
    })
  });
</script>